package cn.kgc.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.kgc.entity.Admin;
import cn.kgc.excpetion.GraceException;
import cn.kgc.form.AdminLoginForm;
import cn.kgc.grace.result.GraceJSONResult;
import cn.kgc.grace.result.ResponseStatusEnum;
import cn.kgc.interceptor.JwtInterceptor;
import cn.kgc.service.AdminService;
import cn.kgc.utils.JwtUtil;
import cn.kgc.vo.AdminVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author YC
 */
@RestController
@RequestMapping({"/admin"})
@Api(value = "管理员认证模块")
@Validated
public class AdminController {

    @Resource
    private AdminService adminService;
    @Resource
    private JwtUtil jwtUtil;

    @PostMapping({"/login"})
    @ApiOperation("管理员登录")
    public GraceJSONResult adminLogin(@Validated @RequestBody AdminLoginForm form) {
        Admin admin = adminService.adminLogin(form.getAdminName(), form.getAdminPassword());
        if (admin == null) {
            GraceException.display(ResponseStatusEnum.ADMIN_LOGIN_ERROR);
        }
        return GraceJSONResult.ok(jwtUtil.createToken(admin.getId(), "ADMIN_BACKEND_LOGIN"));
    }

    @PostMapping({"/info"})
    @ApiOperation("获取管理员信息")
    public GraceJSONResult info() {
        String adminId = JwtInterceptor.adminUserIds.get();
        Admin loginAdmin = adminService.getById(adminId);
        AdminVO adminVo = BeanUtil.copyProperties(loginAdmin, AdminVO.class);
        return GraceJSONResult.ok(adminVo);
    }

}
